<template>
  <view class="detail-container">
    <scroll-view scroll-y class="scroll-view">
      <!-- 基本信息 -->
      <u-form
        labelPosition="left"
        :model="formData"
        ref="formRef"
        class="custom-form"
      >
        <u-form-item label="姓名" prop="name" borderBottom>
          <u-input
            v-model="formData.name"
            placeholder="请输入姓名"
            border="bottom"
          />
        </u-form-item>

        <u-form-item label="大头照" prop="face_image_ids" borderBottom>
          <u-upload
            :fileList="formData.face_image_ids"
            @afterRead="handleUpload('face', $event)"
            @delete="handleDeleteFile('face_image_ids', $event)"
            multiple
            maxCount="2"
            previewFullImage
            deletable
          ></u-upload>
        </u-form-item>

        <u-form-item label="结婚证照片" prop="marriage_image_ids" borderBottom>
          <u-upload
            :fileList="formData.marriage_image_ids"
            @afterRead="handleUpload('marriage', $event)"
            @delete="handleDeleteFile('marriage_image_ids', $event)"
            multiple
            maxCount="2"
            previewFullImage
            deletable
          ></u-upload>
        </u-form-item>

        <!-- 证件上传 -->
        <u-form-item label="身份证照片" prop="idcard_image_ids" borderBottom>
          <u-upload
            :fileList="formData.idcard_image_ids"
            @afterRead="handleUpload('idcard', $event)"
            @delete="handleDeleteFile('idcard_image_ids', $event)"
            multiple
            maxCount="2"
            previewFullImage
            deletable
          ></u-upload>
        </u-form-item>

        <u-form-item label="护照首页" prop="passport_image_ids" borderBottom>
          <u-upload
            :fileList="formData.passport_image_ids"
            @afterRead="handleUpload('passport', $event)"
            @delete="handleDeleteFile('passport_image_ids', $event)"
            maxCount="1"
          ></u-upload>
        </u-form-item>

        <u-form-item label="户口本" prop="household_image_ids" borderBottom>
          <u-upload
            :fileList="formData.household_image_ids"
            @afterRead="handleUpload('household', $event)"
            @delete="handleDeleteFile('household_image_ids', $event)"
            multiple
            maxCount="3"
          ></u-upload>
        </u-form-item>

        <u-form-item label="辅助资产证明" prop="other_image_ids" borderBottom>
          <u-upload
            :fileList="formData.other_image_ids"
            @afterRead="handleUpload('other', $event)"
            @delete="handleDeleteFile('other_image_ids', $event)"
            multiple
            maxCount="5"
          ></u-upload>
        </u-form-item>
      </u-form>

      <view class="footer-btn">
        <u-button
          type="primary"
          @click="handleSubmit"
          shape="circle"
          size="large"
          >保存信息</u-button
        >
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { type ImageItemType } from "@/common/apis/app";
import {
  type ApplicantDetailType,
  type SupplementApplicantTypeEnum,
  getApplicantDetail,
  supplementApplicant,
} from "@/common/apis/applicant";
import { useAppStore } from "@/store/modules/app";

const appStore = useAppStore();

const props = defineProps({
  id: String,
});

const formData = ref<ApplicantDetailType>({
  id: 0,
  name: "",
  identity: "1",
  remark: "",
  face_image_ids: [],
  passport_image_ids: [],
  idcard_image_ids: [],
  household_image_ids: [],
  marriage_image_ids: [],
  other_image_ids: [],
});

async function upload(
  filePath: string,
  type: SupplementApplicantTypeEnum
): Promise<ImageItemType | undefined> {
  const response = await appStore.fetchUploadImage(filePath);
  const response2 = await supplementApplicant({
    id: Number(props.id),
    type,
    image_urls: [response?.url],
  });
  if (response) {
    return response;
  }
}

const fieldMap: Record<SupplementApplicantTypeEnum, any> = {
  face: "face_image_ids",
  marriage: "marriage_image_ids",
  idcard: "idcard_image_ids",
  passport: "passport_image_ids",
  household: "household_image_ids",
  other: "other_image_ids",
};

const handleUpload = async (type: SupplementApplicantTypeEnum, event: any) => {
  const promises: Promise<ImageItemType | undefined>[] = [];
  // 这里实现上传逻辑，实际项目中需要调用API上传到服务器
  event.file.forEach((item: any) => {
    promises.push(upload(item.url, type));
  });

  let uploadRes: (ImageItemType | undefined)[] = [];

  try {
    uni.showLoading({ title: "上传中..." });
    uploadRes = await Promise.all(promises);
    uni.hideLoading();
  } catch (err) {
    uni.hideLoading();
  }

  // @ts-ignore
  formData.value[fieldMap[type]] = [
    // @ts-ignore
    ...formData.value[fieldMap[type]],
    ...uploadRes,
  ];
};

const handleDeleteFile = async (field: string, event: any) => {
  console.log("handleDeleteFile", field, event);
  // @ts-ignore
  formData.value[field].splice(event.index, 1);
  // const result = await appStore.fetchDeleteUploadImage(
  //   Number(props.id),
  //   event.file.id
  // );
  // if (result) {
  //   uni.showToast({ title: "删除成功" });
  //   // @ts-ignore
  //   formData.value[field].splice(event.index, 1);
  // } else {
  //   uni.showToast({ title: "删除失败", icon: "none" });
  //   return;
  // }
};

const handleSubmit = () => {
  // 这里实现保存逻辑
  uni.showToast({ title: "保存成功" });
  setTimeout(() => {
    uni.navigateBack();
  }, 1500);
};

onLoad(async () => {
  const response = await getApplicantDetail(Number(props.id));
  if (response) {
    for (let key in response) {
      if (key.includes("ids")) {
        // @ts-ignore
        response[key] = response[key].map((item: any) => ({
          id: item.id,
          url: item.image_url,
        }));
      }
    }
    formData.value = response;
  }
});
</script>

<style lang="scss" scoped>
.detail-container {
  display: flex;
  flex-direction: column;
  background-color: #f8f8f8;

  .scroll-view {
    flex: 1;
    padding: 20rpx;
    box-sizing: border-box;
  }

  .custom-form {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 0 24rpx;
    margin-bottom: 24rpx;

    ::v-deep .u-form-item {
      padding: 28rpx 0;

      &__body {
        padding-left: 20rpx;
      }
    }
  }

  .footer-btn {
    padding: 0 24rpx;
    margin: 40rpx 0;

    .u-button {
      height: 88rpx;
      font-size: 32rpx;
    }
  }
}
</style>
